package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;
    /**
     * 发送验证码到手机
     *
     */
    @RequestMapping("send2telephone")
    public Result send2telephone(@RequestParam("telephone") String telephone){
        try {
            //通过工具类随机获取一个验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            //调用工具类将验证码发送到手机上
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());
            //设置一个key 用来保存验证码
            String key = telephone + RedisMessageConstant.SENDTYPE_ORDER;
            //将验证码保存到Redis中保存10分钟
            jedisPool.getResource().setex(key,60*10,code.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
    /**
     * 快速登录验证发送
     */
    @RequestMapping("send2login")
    public Result send2login(@RequestParam("telephone") String telephone){
        //通过工具获取一个验证码
        try {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //调用工具将验证码发送到手机上
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code);
            //设置一个key保存该验证码,将验证码保存到Redis中,
            String key = telephone+RedisMessageConstant.SENDTYPE_LOGIN;
            jedisPool.getResource().setex(key,60*10,code);
            return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }

    }
}
